<?php


namespace App\Admin\Forms;

use App\Models\MaterialUnit;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use App\Models\KeywordTwo as Model;

class KeywordTwo extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $key = $this->payload['key'];
        $unit = MaterialUnit::find($key);
        if ($unit->keyword_two_id != 0) {
            Model::find($unit->keyword_two_id)->update(['book_id' => 0, 'unit_id' => 0]);
        }
        $unit->update($input);
        Model::find($input['keyword_two_id'])->update(['book_id' => $unit->materials->id, 'unit_id' => $key]);
        return $this->response()->success('保存成功')->refresh();
    }

    public function form()
    {
        $user = Admin::user();
        if ($user->is_admin==1) {
            $where = [];
        } else {
            $where = ['mechanism_id'=>$user->id];
        }
        $key = $this->payload['key'] ?? null;
        $unit = MaterialUnit::find($key);
        if ($unit->keyword_two_id == 0) {
            $this->select('keyword_two_id', '词汇二')
                ->options(Model::where($where)->pluck('name', 'id')->toArray())
                ->required();
        } else {
            $this->select('keyword_two_id', '词汇二')
                ->options(Model::where($where)->pluck('name', 'id')->toArray())
                ->value($unit->keyword_two_id)
                ->required();
        }
    }
}
